<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row v-show="!switchFlag" class="query-form" style="padding-top: 15px">
        <Col span="8">
          <FormItem label="项目大类：">
            <Input type="text" v-model="form1.categoryName"/>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="项目：">
            <Input type="text" v-model="form1.categoryProjectName"/>
          </FormItem>
        </Col>

        <Col span="8">
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据！" @on-selection-change='getSelectRows'
           :loading="buttonLoading" size="small" border :columns="columns1" :data="dataTable">

      <template slot-scope="{ row }" slot="action">
        <a size="small" style="margin-right: 5px; color:red" @click="selectItem(row)">选择</a>
      </template>
    </Table>


    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>


    <Modal title="查看审计项目内容" v-model="model2" :width=800 :styles="{top: '20px'}">

      <Form :model="showdata" :label-width="160">
        <Row type="flex" justify="space-around" class="detail-background-clor">
          <Col span="11">
            <FormItem label="项目大类名称：">
              {{ showdata.majorName }}
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="项目名称：">
              {{ showdata.itemName }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around">
          <Col span="11">
            <FormItem label="项目分值：">
              {{ showdata.itemScore }}
            </FormItem>
          </Col>
          <Col span="11">

          </Col>
        </Row>

        <Row type="flex" justify="space-around" class="detail-background-clor">
          <Col span="23">
            <FormItem label="审计内容：" prop="planStartTime">
              {{ showdata.subitemName }}
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around">
          <Col span="23">
            <FormItem label="审计标准：" prop="notes">
              {{ showdata.subitemStander }}
            </FormItem>
          </Col>
        </Row>
      </Form>

      <div slot="footer">
        <Button class='ivu-btn-save' @click="onCancel">关闭</Button>
      </div>
    </Modal>
  </layout>
</template>

<script>
import Vue from 'vue'
import {Api} from '@/api/index.js'
var cascaderDom = () => import('@/components/cascader-dom.vue');

export default {
  components: {},
  props: ['templateTypeCode'],
  data() {
    return {
      id:'',
      type:'',
      edit: {
        editIndex: -1 // 当前聚焦的输入框的行数
      },
      //templateTypeCode: '',
      switchFlag: false,
      form1: {},
      //分页参数
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      columns1: [
        {
          type: 'index',
          title: '序号',
          width: 80,
          align: 'center',
        },
        {
          minWidth: 200,
          title: '审计标准',
          key: 'auditName',
          align: 'center'
        },
        {
          minWidth: 200,
          title: '所属二级集团',
          key: 'twoOrgName',
          align: 'center'
        },
        {
          minWidth: 200,
          title: '板块',
          key: 'auditPlate',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '项目大类',
          key: 'categoryName',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '项目',
          key: 'categoryProjectName',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '子项目',
          key: 'projectName',
          align: 'center'
        },
        {
          minWidth: 150,
          title: '标准分值',
          key: 'score',
          align: 'center'
        },


        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 80,
          align: 'center',
          slot: 'action',
        }
      ],
      modelColumns: [
        {
          title: '序号',
          key: 'subitemSeq',
          width: 80,
          align: 'center',
        },
        {
          minWidth: 330,
          title: '审计内容',
          key: 'subitemName',
          align: 'center',
          render: (h, params) => {
            return h('Input', {
              props: {
                type: 'textarea',
                value: params.row.subitemName
              },
              on: {
                'on-change': (event) => {
                  params.row.subitemName = event.target.value;
                  this.form1datacopy.subItemDetails[params.row.subitemSeq - 1] = params.row;
                }
              }
            })
          }
        },
        {
          minWidth: 250,
          title: '评价标准',
          key: 'subitemStander',
          align: 'center',
          render: (h, params) => {
            return h('Input', {
              props: {
                type: 'textarea',
                value: params.row.subitemStander
              },
              on: {
                'on-change': (event) => {
                  params.row.subitemStander = event.target.value;
                  this.form1datacopy.subItemDetails[params.row.subitemSeq - 1] = params.row;
                }
              }
            })
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          fixed: 'right',
          width: 80,
          render: (h, params) => {
            return h('div', [
              h('Icon', {
                props: {
                  type: "ios-trash",
                  size: '20'
                },
                style: {
                  marginRight: "0px"
                },
                on: {
                  click: () => {
                    this.deleteDetail(params.index);
                  }
                }
              })
            ]);
          }
        }
      ],
      itemIdList: [],
      majorIdList: [],
      currentOrgId: '',
      currentOrgName: '',
      setCurrentName: {},
      ruleCustom: {
        majorId: [
          {required: true, message: '  ', trigger: 'blur'}
        ],
        itemId: [
          {required: true, message: '  ', trigger: 'blur'}
        ]
      },
      ruleCustom1: {
        majorId: [
          {required: true, message: '  ', trigger: 'blur'}
        ],
        itemName: [
          {required: true, message: '  ', trigger: 'blur'}
        ],
        itemScore: [
          {required: true, message: '  ', trigger: 'blur'}
        ]
      },
      form1datacopy: {
        subItemDetails: []
      },
      form1ItemData: {
        subItemDetails: []
      },
      teamTypes: [],
      resLevels: [],
      dataTable: [],
      showdata: {},
      model1: false,
      model2: false,
      model3: false,
      add: false,
      buttonLoading: false, tableHeight: 10,
      deleteRows: [],
    }
  },

  created: function () {
    // this.templateTypeCode = this.$route.query.templateType
    this.selectCodingSort();
  },

  mounted: function () {
    this.tableHeight = window.innerHeight - 220;
  },
  methods: {
    selectItem(row) {
      let data = JSON.parse(JSON.stringify(row));
      data.executorId  = this.id;
      data.type = this.type;
      this.$emit('getActivityData', data);
    },
    onCancel() {
      this.model2 = false
    },
    handleEdit(row, index) {
      this.edit = {...this.edit, ...row}
      this.edit.editIndex = index;
    },
    deleteDetail(index) {
      this.form1datacopy.subItemDetails.splice(index, 1);

      this.form1datacopy.subItemDetails.forEach((item, index, array) => {
        item.subitemSeq = index + 1
      })
    },
    addRow() {
      let num = this.form1datacopy.subItemDetails.length + 1
      var item = {
        subitemSeq: num,
        subitemName: "",
        subitemStander: ''
      }
      this.form1datacopy.subItemDetails.push(item);
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = window.innerHeight - 220;
      } else {
        this.tableHeight = window.innerHeight - 315;
      }
    },
    selectCodingSort1(val) {
      let data = {majorId: val}
      this.$http.get(Api.getAuditTemplateItems, {params: data}).then((res) => {
        this.itemIdList = res.data.data;

        // if(this.itemIdList){
        //    console.log('aaaaaaaaaa',this.itemIdList)
        // }

      })

    },
    selectCodingSort() {
      let data = {
        templateTypeCode: this.templateTypeCode
      }
      this.$http.get(Api.getAuditTemplatePageInit, {params: data}).then((res) => {
        this.majorIdList = res.data.data;

        if (this.majorIdList) {
          //this.majorIdList.unshift({majorId:-1,majorName:"全部"})
        }

      })

      // this.$http.get(Api.queryCodeDetailBySortId + '/STY-000011', {params: {}}).then((res) => {
      //     this.teamTypes = res.data.data;
      // })
      // this.$http.get(Api.queryCodeDetailBySortId + '/RL-000011', {params: {}}).then((res) => {
      //     this.resLevels = res.data.data;
      // })
    },

    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    showData1(row) {
      this.showdata = row;
      this.model2 = true;
    },



    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    removeTemp(row) {
      let url = Api.deleteAuditTemplateSub + '/' + row.subitemId;
      this.$http.get(url, {}).then((res) => {
        this.$Message.success('成功');
        this.query()
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },
    load(id,type){
      this.id = id;
      this.type = type;
      this.query();
    },

    query() {
      this.buttonLoading = true
      let data = {
        currentPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        standardId:this.id,
        type:this.templateTypeCode
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      let url = Api.queryAuditTemplate;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data;
        this.pagedata.total = res.data.totalSize;
        this.buttonLoading = false
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    reset() {

      this.form1 = {}
      this.pagedata.currentPage = 1;
      this.query();
    },
    handleCancel3() {
      this.form1ItemData = {};
      this.model3 = false;
    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
    },
    submit3(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$http.post(Api.createAuditTemplateItem, this.form1ItemData).then((res) => {
            this.$Message.success("保存成功")
            this.model3 = false;
            this.query();

          }).catch(e => {
            this.model3 = false;
            this.query();
            this.$Message.error("数据获取失败")
          })
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    submit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {

          if (!this.form1datacopy.subItemDetails || this.form1datacopy.subItemDetails.length === 0) {
            this.$Message.warn("请添加审计内容")
            return
          }

          this.$http.post(Api.createAuditTemplate, this.form1datacopy).then((res) => {
            this.$Message.success("保存成功")
            this.model1 = false;
            this.query();

          }).catch(e => {
            this.model1 = false;
            this.query();
            this.$Message.error("数据获取失败")
          })
        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    addItemInfo() {
      this.form1datacopy = {};
      this.model3 = true;
    },
    addInfo() {
      this.form1datacopy = {};
      Vue.set(this.form1datacopy, 'subItemDetails', [])

      this.model1 = true;
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
  },
  watch: {
    // $route(){
    //     this.templateTypeCode = this.$route.query.templateType
    //     this.selectCodingSort();
    //     this.query()
    // },
    "model1": function (qw, er) {
      if (qw && this.model1) {
        setTimeout(() => {
          //this.$refs.carOrg.setCurrentOrg();
          //this.$refs.childUser.setCurrentUser();
        }, 100)
      } else {
        //this.$refs.carOrg.setCurrentOrg();
        //this.$refs.childUser.setCurrentUser();
      }
    },

  },
}
</script>
<style scoped>
@import '../../../index.css';
</style>
